package dns

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"

	"github.com/folk113/aliddns/config"
)

type IpAddress struct {
	IP      string `json:"ip"`
	GeoIp   string `json:"geo-ip"`
	ApiHelp string `json:"API Help"`
}
type CityIpAddress struct {
	Cip   string `json:"cip"`
	Cid   string `json:"cid"`
	Cname string `json:"cname"`
}

func GetCityIp() (string, error) {
	url := "http://pv.sohu.com/cityjson?ie=utf-8"
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("err: ", err)
		return "", errors.New("http client error!")
	}
	client := &http.Client{}

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("err: ", err)
		return "", errors.New("http get error!")
	}
	var ipAddress CityIpAddress
	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("err: ", err)
		return "", errors.New("read data error!")
	}
	data = bytes.SplitAfter(data, []byte("="))[1]
	data = bytes.ReplaceAll(data, []byte(";"), []byte(" "))
	err = json.Unmarshal(data, &ipAddress)
	if err != nil {
		println("jsondata: " + string(data))
		fmt.Println("err: ", err)
		return "", errors.New("json dataerror!")
	}
	return ipAddress.Cip, err
}

func TaobaoGetIp() (string, error) {
	url := "https://www.taobao.com/help/getip.php"
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("err: ", err)
		return "", errors.New("http client error!")
	}
	client := &http.Client{}

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("err: ", err)
		return "", errors.New("http get error!")
	}
	var ipAddress string
	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("err: ", err)
		return "", errors.New("read data error!")
	}
	buf := string(data)
	reg := regexp.MustCompile(`\d+\.\d+.\d+.\d+`) //ipCallback({ip:"113.110.166.143"})
	if reg == nil {
		fmt.Println("err: ", err)
		return "", errors.New("regexp error!")
	}
	result := reg.FindAllStringSubmatch(buf, -1)
	if result == nil {
		println("ipdata: " + string(data))
		return "", errors.New("can not found ip.")
	} else {
		ipAddress = result[0][0]
		return ipAddress, nil
	}
}

func GetIp() (string, error) {
	ipaddr, err := GetCityIp()
	if err == nil {
		println("sohu ipaddr: " + ipaddr)
		return ipaddr, err
	}
	ipaddr, err = TaobaoGetIp()
	if err == nil {
		println("taobao ipaddr: " + ipaddr)
		return ipaddr, err
	}
	println("jsonip ipaddr: ")
	url := "https://ipv4.jsonip.com"
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		config.Log.Error(err)
	}
	client := &http.Client{}

	response, err := client.Do(request)
	if err != nil {
		config.Log.Error(err)
	}
	ipAddress := IpAddress{}
	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		config.Log.Error(err)
	}
	err = json.Unmarshal(data, &ipAddress)
	if err != nil {
		config.Log.Error(err)
	}
	return ipAddress.IP, err
}
